package com.sense.kukoo.biz_explore.view

import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.SearchView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.arouter.utils.TextUtils
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.biz_explore.R
import com.sense.kukoo.biz_explore.adapter.SearchAdapter
import com.sense.kukoo.biz_explore.vm.SearchViewModel
import com.sense.kukoo.biz_explore.databinding.BizExploreActivitySearchBinding
import com.sense.kukoo.common.anim.BottomPlayerAnimHelper
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.event.UserEditEvent
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.bean.SearchBean
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.common.repo.http.bean.UserSearchBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.utils.KeyBoardUtils
import com.sense.kukoo.common.wiget.dialog.BottomLoginDialog
import com.sense.kukoo.common.wiget.state.NetworkErrorState
import com.sense.kukoo.common.wiget.state.SearchInputState
import com.sense.kukoo.common.wiget.state.SearchNoResultState
import com.sense.kukoo.lib_logger.LoggerManager
import com.zy.multistatepage.MultiStateContainer
import com.zy.multistatepage.bindMultiState
import com.zy.multistatepage.state.SuccessState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = ARouterUrl.ROUTE_EXPLORE_MODULE_SEARCH_ACTIVITY)
class SearchActivity : BaseMvvmActivity<SearchViewModel, BizExploreActivitySearchBinding>() {

    private val TAG = SearchActivity::class.simpleName

    private var mAdapter: SearchAdapter? = null
    private var flagToRefresh = false
    private val mBottomPlayerAnimHelper = BottomPlayerAnimHelper()

    var mCurrentMusic: LocalMediaListItemBean? = null
    var mCurrentPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING

    override fun getLayoutId(): Int = R.layout.biz_explore_activity_search

    override fun getViewModelClass(): Class<SearchViewModel> = SearchViewModel::class.java

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        setSupportActionBar(mBinding.toolBar)
        //
        mViewModel.mHintList.observe(this) {
            mAdapter?.list = it
            mAdapter?.notifyDataSetChanged()
        }
        mViewModel.mSearchResultList.observe(this){
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
            if (it.size == 0) {
                refreshState(STATE_NO_RESULT)
            }else{
                refreshState(STATE_SUCCESS)
                mAdapter?.list = it
                mAdapter?.notifyDataSetChanged()
            }
        }
        mViewModel.mEnableLoadMore.observe(this){
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
        mViewModel.mEnableRefresh.observe(this){
            mBinding.refreshLayout.setEnableRefresh(it)
        }
        bindAction(mViewModel.action_refreshPosition){
            mAdapter?.notifyItemChanged(it)
        }
        bindAction(mViewModel.action_networkError){
            refreshState(STATE_NO_NET)
        }
    }

    override fun initView() {
        mBinding.cancel.setOnClickListener {
            finish()
        }
        //
        mBinding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                if (!android.text.TextUtils.isEmpty(query)) {
                    mViewModel.getSearchData(query!!)
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if (TextUtils.isEmpty(newText)) {
                    refreshState(STATE_SUCCESS)
                    mViewModel.showHintData()
                } else {
                    refreshState(STATE_INPUT_TEXT)
                    mViewModel.showHintData()
                }
                return false
            }
        })
        //
        val mutableListOf = mutableListOf<SearchBean>()
        mAdapter = SearchAdapter(mListener, mutableListOf)
        mBinding.recyclerView.adapter = mAdapter
        //
        val linearLayoutManager = LinearLayoutManager(this)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            mViewModel.refreshSearch()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            mViewModel.getMoreSearchData()
        }
        //
        mBinding.flContent.setOnTouchDown {
            LoggerManager.d(TAG, "OnTouchDown ---> closeKeybord")
            KeyBoardUtils.closeKeybord(mBinding.searchView.editText, this)
            mBinding.searchView.editText.clearFocus()
        }
        //
        initUserId()
        //
        initMusicPlayer()
        //
        mBinding.searchView.requestFocus()
        //首次加载
        mViewModel.getHintData()
    }

    private fun initUserId(){
        val userID = Repo.user.get()?.id ?: 0
        mAdapter?.setCurrentUserId(userID)
    }

    private fun initMusicPlayer(){
        mBottomPlayerAnimHelper.setPlayerView(mBinding.musicPlayer)
        //
        mBinding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            private var isScroll = false

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                if (isScroll) {
                    mBottomPlayerAnimHelper.dispatchScrollEvent(dy, RecyclerView.SCROLL_STATE_DRAGGING)
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    isScroll = false
                    mBottomPlayerAnimHelper.dispatchScrollEvent(0, RecyclerView.SCROLL_STATE_IDLE)
                } else {
                    isScroll = true
                }
            }
        })
        //
        mBinding.musicPlayer.alpha = 0F
        mBinding.musicPlayer.animate()
            .alpha(1F)
            .setDuration(400L)
            .withEndAction {
                val maxTranslationY = mBinding.musicPlayer.height.toFloat() + ApplicationContext.dp2px(16F)
                mBottomPlayerAnimHelper.setMaxTranslationY(maxTranslationY)
                //LoggerManager.d(TAG, "maxTranslationY=${maxTranslationY}")
            }
            .start()
    }

    val mListener = object : SearchAdapter.SearchEventListener {

        override fun onRecommendItemClick(bean: SearchBean, position: Int, text: String) {
            mBinding.searchView.setQuery(text, true)
        }

        override fun onRecentCleanAll() {
            mViewModel.setCleanAll()
        }

        override fun onRecentItemClick(bean: SearchBean) {
            mBinding.searchView.setQuery(bean.keyword, true)
        }

        override fun onRecentItemDelete(bean: SearchBean) {
            mViewModel.setDeleteRecentSearch(bean)
        }

        override fun onSearchResultContentItemClick(bean: SearchBean) {
            val data: IndexContentBean = bean.content!!
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.id}")
                .navigation()
        }

        override fun onSearchResultChannelClick(bean: SearchBean) {
            val userId:Long = bean.content?.userId ?: bean.user?.id ?: 0L
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CHANNEL_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${userId}")
                .navigation()
            //
            flagToRefresh = true
        }

        override fun onSearchResultPlayClick(bean: SearchBean) {
            val data:IndexContentBean = bean.content!!
            if(mCurrentMusic?.idOfChapter() == data.id){
                //当前的
                when (mCurrentPlayState) {
                    UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                    UserWatcher.MusicStateWatcher.STATE_SEEKING,
                    UserWatcher.MusicStateWatcher.STATE_PREPARE,
                    UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                        Kukoo.input.pause()
                    }
                    /*UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{}
                    UserWatcher.MusicStateWatcher.STATE_PAUSE ->{}*/
                    else -> {
                        Kukoo.input.start()
                    }
                }
            } else {
                //非当前的
                Kukoo.input.play(LocalMediaListItemBean(data))
            }
        }

        override fun onSearchResultFollowClick(bean: SearchBean, position: Int) {
            //检测是否登陆
            if (BottomLoginDialog.autoCheckAndLogin(this@SearchActivity)){
                //进行订阅
                val data: UserSearchBean = bean.user!!
                mViewModel.subscription(data, position)
            }
        }
    }

    override fun responseVM(action: Int) {}

    override fun onResume() {
        super.onResume()
        //
        mBottomPlayerAnimHelper.animateToShow()
        if (flagToRefresh) {
            flagToRefresh = false
            mViewModel.refreshSearchOnLogin()
        }
    }

    val STATE_SUCCESS:Int = 1
    val STATE_NO_NET:Int = 2
    val STATE_NO_RESULT:Int = 3
    val STATE_INPUT_TEXT:Int = 4
    var currentState:Int = STATE_SUCCESS

    private fun refreshState(newState: Int) {
        if (currentState == newState) {
            return
        }
        currentState = newState

        when (newState) {
            STATE_SUCCESS -> {
                mBinding.multiStateContainer.show<SuccessState>()
            }
            STATE_NO_RESULT -> {
                mBinding.multiStateContainer.show<SearchNoResultState>()
            }
            STATE_NO_NET -> {
                ToastUtils.showToast(getString(com.sense.kukoo.common_i18n.R.string.search_no_net_toast))
                mBinding.multiStateContainer.show<NetworkErrorState> {
                    it.onRetry {
                        mViewModel.refreshSearch()
                    }
                }
            }
            STATE_INPUT_TEXT -> {
                mBinding.multiStateContainer.show<SearchInputState>()
            }
            else -> {}
        }
    }

    private val mWatcher = object: UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            mAdapter?.setCurrentMusic(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentPlayState = state
            mAdapter?.setCurrentPlayState(state)
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        initUserId()
        mViewModel.refreshSearchOnLogin()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        Kukoo.watcher.register(mWatcher)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        Kukoo.watcher.unregister(mWatcher)
    }

}